<?php

namespace App\Console\Commands;

use App\Models\CountryModel;
use App\Models\lazada\BigBagModel;
use App\Models\lazada\OrderModel;
use App\Models\lazada\LogModel;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class Lazada extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'lazada';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $order_insert = []; $big_bag_data = [];
        for($i=0; $i < 30; $i++){
            $pop = Redis::lpop('lazada_log');
            if($pop){
                $item = json_decode($pop, true);

                $log = New LogModel();
//                $log->data = json_encode($item['data']);
                $log->ip = $item['ip'];
                $log->type = $item['type'];
                $log->header = json_encode($item['header']);
                $log->uri = $item['uri'];
                $log->sign = $item['sign'];
                $log->platform = 'lazada';
                $log->get_time = $item['time'] ?? date('Y-m-d H:i:s');
                $log->save();

                $data = $item['data'];
                if($item['type'] == 'bigbag'){
                    $big_bag_data[] = [
                        'data' => $data,
                        'time' => $item['time'],
                    ];
//                    $this->bigbag($data, $item['time']);
                }else{

                    $idempotentId = $data['idempotentId'] ?? '';
                    $find = OrderModel::where('idempotentId', $idempotentId)->first();
                    if(!$find){
                        $order_insert[] = $this->order($data, $item['time']);
                        echo "小包：" . $data['orderCode'];
                    }

                }

            }else{
                break;
            }
        }

        if($order_insert){
            OrderModel::insert($order_insert);
        }

        if($big_bag_data){
            foreach ($big_bag_data as $item){
                $idempotentId = $item['data']['idempotentId'] ?? '';
                $find = BigBagModel::where('idempotentId', $idempotentId)->first();
                if(!$find) {
                    $this->bigbag($item['data'], $item['time']);
                };

            }
        }

        return Command::SUCCESS;
    }


    public function bigbag($data, $time =  null)
    {

        $customer_id = 75;

        $notify = new BigBagModel();
        $notify->platform = 'lazada';
        $notify->customer_id = $customer_id;
        $notify->parcelList = isset($data['parcelList']) ? json_encode($data['parcelList']) : '';
        $notify->bigBagID = $data['bigBagID'];
        $notify->parcelQty = $data['parcelQty'];
        $notify->trackingNumber = $data['trackingNumber'];
        $notify->features = isset($data['features']) ? json_encode($data['features']) : '';
        $notify->bigBagWeight = $data['bigBagWeight'] ?? 0;
        $notify->weightUnit = $data['weightUnit'] ?? '';
        $notify->bigBagVolume = $data['bigBagVolume'] ?? 0;
        $notify->bigBagLength = $data['bigBagLength'] ?? 0;
        $notify->bigBagWidth = $data['bigBagWidth'] ?? 0;
        $notify->bigBagHeight = $data['bigBagHeight'] ?? 0;
        $notify->dimensionUnit = $data['dimensionUnit'] ?? '';
        $notify->cargoType = $data['cargoType'] ?? 0;
        $notify->fromLocation = $data['fromLocation'] ?? '';
        $notify->toLocation = $data['toLocation'] ?? '';
        $notify->idempotentId = $data['idempotentId'] ?? '';
        $notify->router = $data['router'] ?? '';


        //更新小包的打包号
        if(isset($data['parcelList'])){
            $orderCode = [];
            foreach ($data['parcelList'] as $parcel){
                $orderCode[] = $parcel['orderCode'];
            }

            OrderModel::whereIn('orderCode', $orderCode)->update([
                'bigBagID' => $notify->bigBagID
            ]);
        }

        //目的地机场
        if($data['toLocation']){
            $arr = explode(' ', $data['toLocation']);
            if(count($arr) > 1){
                $notify->destination = $arr[1];
            }else{
                $notify->destination = $data['toLocation'];
            }
        }

        $notify->data = json_encode($data);
        $notify->get_time = $time ?? date('Y-m-d H:i:s');
        $notify->save();

        echo "大包：" . $data['bigBagID'];

    }


    public function order($data, $time = null)
    {

        $customer_id = 75;

        $asn = [
            'platform' => 'lazada',
            'customer_id' => $customer_id,
            'trackingNumber' => $data['trackingNumber'] ?? '',
            'receiver' => isset($data['receiver']) ? json_encode($data['receiver']) : '',
            'sender' => isset($data['sender']) ? json_encode($data['sender']) : '',
            'preResInfo' => isset($data['preResInfo']) ? json_encode($data['preResInfo']) : '',
            'nextResInfo' => isset($data['nextResInfo']) ? json_encode($data['nextResInfo']) : '',
            'parcel' => isset($data['parcel']) ? json_encode($data['parcel']) : '',
            'tradeOrderId' => $data['tradeInfo']['tradeOrderId'] ?? '',
            'idempotentId' => $data['idempotentId'] ?? '',
            'orderCode' => $data['orderCode'] ?? '',
            'features' => isset($data['features']) ? json_encode($data['features']) : '',
            'taxId' => $data['taxId'] ?? '',
            'fromLocation' => $data['fromLocation'] ?? '',
            'toLocation' => $data['toLocation'] ?? '',
            'resCode' => $data['preResInfo']['resCode'] ?? '',
            'weight' => $data['parcel']['weight'] ?? 0,
            'price' => $data['parcel']['price'] ?? 0,
            'priceUnit' => $data['parcel']['priceUnit'] ?? '',
            'router' => $data['router'] ?? '',


        ];

        //目的地国家
        if(isset($data['receiver']['address']['country'])){
            $asn['des_country_code'] = $data['receiver']['address']['country'];
        }

        //货物属性
        if(isset($data['parcel']['goodsList'])){
            $asn['goods_attr'] = $data['parcel']['goodsList'][0]['cargoType'] ?? 1;
        }

        //目的地机场
        if($data['toLocation']){
            $arr = explode(' ', $data['toLocation']);
            if(count($arr) > 1){
                $asn['destination'] = $arr[1];
            }else{
                $asn['destination'] = $data['toLocation'];
            }
        }

        $asn['data'] = json_encode($data);
        $asn['created_at'] = date('Y-m-d H:i:s');
        $asn['get_time'] = $time ?? date('Y-m-d H:i:s');

        return $asn;


    }
}
